//
//  NavigateView.m
//  SecondPage
//
//  Created by winston on 13-4-24.
//  Copyright (c) 2013年 winston. All rights reserved.
//

#import "NavigateView.h"
#import "NavigateItem.h"



@implementation NavigateView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        
        colorLabel = [[UILabel  alloc] initWithFrame:CGRectMake(-10, 0, NAVIGATEITEMWIDTH+20, 20)];
        [self addSubview:colorLabel];
        [colorLabel release];
        [colorLabel setBackgroundColor:[UIColor clearColor]];
        colorLabel.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
        colorLabel.font = [UIFont systemFontOfSize:14];
        colorLabel.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

-(void)loadData:(NSArray*)data
{
    for(UIView * item in self.subviews)
    {
        if ([item isKindOfClass:[NavigateItem class]]) {
            [item removeFromSuperview];
        }
        
    }
    
    if(data==nil||[data count]<1) return;
    
    NSInteger count = [data count];
    CGFloat left = (self.frame.size.width-count*(NAVIGATEITEMWIDTH+NAVIGATEMARGIN))/2;
    
    NavigateItem * item = nil;
    
    for(NSInteger i= 0;i<count;i++)
    {
        NSDictionary * dic = [data objectAtIndex:i];
        item = [[NavigateItem alloc]initWithFrame:CGRectMake(left, 0, NAVIGATEITEMWIDTH, NAVIGATEITEMHEIGHT)];
        [item setCategory:[dic objectForKey:@"category"] withImage:[dic objectForKey:@"categoryimg"]];
        item.colorName = [dic objectForKey:@"colorname"];
        [item addTarget:self action:@selector(onNavigate:) forControlEvents:UIControlEventTouchUpInside];
        [item setTag:i+100];
        [self addSubview:item];
        [item release];
        left+=NAVIGATEITEMWIDTH+NAVIGATEMARGIN;
    }
}

-(void)selectIndex:(NSInteger)index
{
    for(NavigateItem * item in self.subviews)
    {
        if(item.tag == index+100)
        {
            [self onNavigate:item];
            break;
        }
    }
}

-(void)onNavigate:(NavigateItem*)sender
{
    if(sender.selected) return;
    
    for(NavigateItem * item in self.subviews)
    {
        if ([item isKindOfClass:[NavigateItem class]]) {
            item.selected = FALSE;
        }
    }
    
    sender.selected = TRUE;
    colorLabel.center = CGPointMake(sender.center.x, sender.center.y+40);
    colorLabel.text = sender.colorName;
    
    [self.superview performSelector:@selector(selectCategory:) withObject:[NSNumber numberWithInt:sender.tag-100]];
}


@end
